<?php

namespace App\Utils;

class MessageEngine
{
    /**
     * 新订单来了
     * @param $data
     * @return array
     */
    public static function register($data)
    {
        $data['type'] = 'register';
        return self::api('message/push', ['user_ids' => 'all', 'content' => json_encode($data)]);
    }

    /**
     * 新订单来了
     * @param $data
     * @return array
     */
    public static function message($data)
    {
        $data['type'] = 'message';
        return self::api('message/push', ['user_ids' => 'all', 'content' => json_encode($data)]);
    }

    /**
     * 新订单来了
     * @param $data
     * @return array
     */
    public static function card($data)
    {
        $data['type'] = 'card';
        return self::api('message/push', ['user_ids' => 'all', 'content' => json_encode($data)]);
    }

    /**
     * @param $url
     * @param $postData
     * @return array;
     */
    public static function api($url, $postData)
    {
        if (config('message.disable')) {
            return [];
        }
        try {
            $ch = curl_init();
            curl_setopt($ch, CURLOPT_TIMEOUT, 60);
            curl_setopt($ch, CURLOPT_URL, config('message.server_address') . $url);
            curl_setopt($ch, CURLOPT_HEADER, false);
            curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
            curl_setopt($ch, CURLOPT_POST, true);
            curl_setopt($ch, CURLOPT_POSTFIELDS, $postData);
            $result = curl_exec($ch);
            curl_close($ch);
            return json_decode($result, true);
        } catch (\Exception $exception) {
            \Illuminate\Support\Facades\Log::error($exception->getMessage() . "\r\n" . $exception->getTraceAsString());
        }
        return [];
    }
}